package com.chao.product.util;

import com.chao.model.PmsProduct;
import com.exception.LocalCacheException;
import com.google.common.cache.*;
import com.google.common.graph.Graph;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.security.Key;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class LocalCache<T> {

    Cache<String,T> cache = null;

    @PostConstruct
    public void initCache(){
         cache = CacheBuilder.newBuilder()
                //设置缓存的数目
                .maximumSize(100)
                //设置缓存的过期时间 这个时间段内没有被 读写的数据会被清除
                .expireAfterAccess(300,TimeUnit.SECONDS)
                .concurrencyLevel(10)
                .initialCapacity(10)
                .removalListener(new RemovalListener<Object, Object>() {
                    @Override
                    public void onRemoval(RemovalNotification<Object, Object> removalNotification) {
                       log.info("移除本地缓存" , removalNotification.getCause());
                    }
                })
                .build();
    }

    public void setLocalCache(String key,T t){
        cache.put(key,t);
    }

    public T getLocalCache(String key){
        return cache.getIfPresent(key);
    }

    public void remove(String key){
        cache.invalidate(key);
    }

    public void get(String key){
        cache.getIfPresent(key);
    }
}
